package com.wxzz.elearning.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.wxzz.elearning.common.dto.FeignEnterpriseDto;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanCompare {


    public static void main(String[] args) throws Exception {
        FeignEnterpriseDto f1 = new FeignEnterpriseDto();
        f1.setBusinessCategoryId(1L);
        FeignEnterpriseDto f2 = new FeignEnterpriseDto();
        List<Map<String, String>> listData = getListData(f1, f2);
        for (Map<String, String> listDatum : listData) {
            FeignEnterpriseDto o = (FeignEnterpriseDto)mapToBean(listDatum, FeignEnterpriseDto.class);
            System.out.println(o.toString());
            System.out.println(listDatum);
        }
    }

    /***
     * 通过类反射比较两个对象的不同
     * @param user1
     * @param user2
     * @return
     */
    public static List<Map<String, String>> getListData(Object user1, Object user2) {
        Map<String, String> orgobj = new HashMap<String, String>();
        Map<String, String> nowobj = new HashMap<String, String>();
        Field[] fs = user1.getClass().getDeclaredFields();
        for (Field f : fs) {
            f.setAccessible(true);
            Object v1 = null;
            Object v2 = null;
            try {
                v1 = f.get(user1);
                v2 = f.get(user2);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //拿到属性的类型
			/*String type = f.getGenericType().toString();
            System.out.println(type);*/

            //if (!f.getType().equals(List.class)) {}// 不匹配list类型

            if (!equals(v1, v2)) {
                //两个对象相同属性不相同值的数据加入map中
                if (v1 != null) {
                    orgobj.put(f.getName(), v1.toString());
                }
                if (v2 != null) {
                    nowobj.put(f.getName(), v2.toString());
                }
            }
        }

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        list.add(orgobj);//原来的对象属性值
        list.add(nowobj);//改变的对象属性值
        return list;
    }

    public static boolean equals(Object obj1, Object obj2) {
        if (obj1 == obj2) {
            return true;
        }
        if (obj1 == null || obj2 == null) {
            return false;
        }
        return obj1.equals(obj2);
    }

    /**
     * 利用反射将map集合封装成bean对象
     *
     *
     * @param map
     * @param clazz
     * @return
     */
    public static <T> T mapToBean(Map<String, String> map, Class<?> clazz) throws Exception {
        Object obj = clazz.newInstance();
        if (map != null && !map.isEmpty() && map.size() > 0) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String propertyName = entry.getKey(); 	// 属性名
                Object value = entry.getValue();		// 属性值
                String setMethodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
                Field field = getClassField(clazz, propertyName);	//获取和map的key匹配的属性名称
                if (field == null){
                    continue;
                }
                Class<?> fieldTypeClass = field.getType();
                value = convertValType(value, fieldTypeClass);
                try {
                    clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }
        return (T) obj;
    }

    /**
     * 根据给定对象类匹配对象中的特定字段
     * @param clazz
     * @param fieldName
     * @return
     */
    private static Field getClassField(Class<?> clazz, String fieldName) {
        if (Object.class.getName().equals(clazz.getName())) {
            return null;
        }
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }
        Class<?> superClass = clazz.getSuperclass();	//如果该类还有父类，将父类对象中的字段也取出
        if (superClass != null) {						//递归获取
            return getClassField(superClass, fieldName);
        }
        return null;
    }

    /**
     * 将map的value值转为实体类中字段类型匹配的方法
     * @param value
     * @param fieldTypeClass
     * @return
     */
    private static Object convertValType(Object value, Class<?> fieldTypeClass) {
        Object retVal = null;

        if (Long.class.getName().equals(fieldTypeClass.getName())
                || long.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Long.parseLong(value.toString());
        } else if (Integer.class.getName().equals(fieldTypeClass.getName())
                || int.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Integer.parseInt(value.toString());
        } else if (Float.class.getName().equals(fieldTypeClass.getName())
                || float.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Float.parseFloat(value.toString());
        } else if (Double.class.getName().equals(fieldTypeClass.getName())
                || double.class.getName().equals(fieldTypeClass.getName())) {
            retVal = Double.parseDouble(value.toString());
        } else {
            retVal = value;
        }
        return retVal;
    }
}
